package com.wang.mall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wang.mall.constant.CartConstant;
import com.wang.mall.dto.ProductDto;
import com.wang.mall.feign.ProductFeignService;
import com.wang.mall.model.R;
import com.wang.mall.service.CartService;
import com.wang.mall.vo.CartItemVo;
import com.wang.mall.vo.CartRedisVo;
import com.wang.mall.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;


    @Override
    public boolean addCart(CartVo cartVo) {

        Long productId = cartVo.getProductId();
        Integer count = cartVo.getCount();
        Long memberId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());


        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(CartConstant.CART_PREFIX);
        // 根据会员ID查询购物查信息
        String res = (String) cartOps.get(memberId.toString());
        if (StringUtils.isEmpty(res)) {
            // 用户没有购物车, 生成购物车并添加商品
            CartRedisVo cartRedisVo = new CartRedisVo();
            // 远程查询, 商品信息
            R info = productFeignService.info(productId);
            ProductDto product = R.getDataForJson(info.getData(), new TypeReference<ProductDto>() {
            });

            // 创建购物车项
            CartItemVo itemVo = new CartItemVo();
            itemVo.setCheck(true);
            itemVo.setCount(count);
            itemVo.setPrice(product.getPrice());
            itemVo.setProductId(productId);
            itemVo.setTitle(product.getTitle());
            BigDecimal total = product.getPrice().multiply(new BigDecimal(count)).setScale(2, BigDecimal.ROUND_HALF_UP);
            itemVo.setTotalPrice(total);
            itemVo.setImgUrl(product.getImageList().get(0).getUrl());

            // 创建购物车
            cartRedisVo.setItems(Arrays.asList(itemVo));
            cartRedisVo.setMemberId(memberId);
            cartRedisVo.setTotalAmount(total);
            cartRedisVo.setCountNum(count);

            // 添加到redis
            String s = JSON.toJSONString(cartRedisVo);
            cartOps.put(memberId.toString(), s);
            return true;
        } else {
            // 用户有购物车
            // 获取用户购物车信息
            String o = (String) cartOps.get(memberId.toString());
            CartRedisVo cartRedisVo = JSON.parseObject(o, CartRedisVo.class);
            // 判断用户的购物车中有没有这个商品
            List<CartItemVo> items = cartRedisVo.getItems();


            boolean doesItContain = false; //是否包含
            int productIndex = 0;
            int countProduct = 0;
            BigDecimal countPrice = new BigDecimal(0);
            for (int i = 0; i < items.size(); i++) {
                CartItemVo cartItemVo = items.get(i);
                if (cartItemVo.getProductId().equals(productId)) {
                    doesItContain = true;
                    productIndex = i;
                    break;
                }
            }
            if (doesItContain) { //购物车中包含当前商品

                cartRedisVo.setCountNum(items.size());
                // 购物车中包含当前商品 // 重新设置商品信息
                CartItemVo cartItemVo = items.get(productIndex);
                cartItemVo.setCount(count);
                BigDecimal total = cartItemVo.getPrice().multiply(new BigDecimal(count)).setScale(2, BigDecimal.ROUND_HALF_UP);
                cartItemVo.setTotalPrice(total);


                // 清空购物车中的信息
                // cartOps.delete(memberId.toString());


                // 重新计算总价格和商品总数量
                for (CartItemVo item : items) {
                    if (item.getCheck()) { // 判断商品是否选中
                        countProduct += item.getCount(); // 计算总数量
                        countPrice = countPrice.add(item.getTotalPrice());
                    }
                }

                cartRedisVo.setCountNum(countProduct);
                cartRedisVo.setTotalAmount(countPrice);
                cartRedisVo.setItems(items);

                // 将新的数据重新添加回购物车
                String s = JSON.toJSONString(cartRedisVo);
                cartOps.put(memberId.toString(), s);
                return true;
            } else {
                // 购物车中不包含当前商品的信息
                // 创建商品详情
                // 远程查询, 商品信息
                R info = productFeignService.info(productId);
                ProductDto product = R.getDataForJson(info.getData(), new TypeReference<ProductDto>() {
                });

                // 创建购物车项
                CartItemVo itemVo = new CartItemVo();
                itemVo.setCheck(true);
                itemVo.setCount(count);
                itemVo.setPrice(product.getPrice());
                itemVo.setProductId(productId);
                itemVo.setTitle(product.getTitle());
                BigDecimal total = product.getPrice().multiply(new BigDecimal(count)).setScale(2, BigDecimal.ROUND_HALF_UP);
                itemVo.setTotalPrice(total);
                itemVo.setImgUrl(product.getImageList().get(0).getUrl());

                //将商品添加到购物车
                cartRedisVo.getItems().add(itemVo);

                // 重新计算总价格和商品总数量
                for (CartItemVo item : items) {
                    if (item.getCheck()) {
                        countProduct += item.getCount(); // 计算总数量
                        countPrice = countPrice.add(item.getTotalPrice());
                    }
                }

                cartRedisVo.setCountNum(countProduct);
                cartRedisVo.setTotalAmount(countPrice);
                cartRedisVo.setItems(items);
                // 将新的数据重新添加回购物车,写回redis
                String s = JSON.toJSONString(cartRedisVo);
                cartOps.put(memberId.toString(), s);
                return true;
            }
        }
    }

    /**
     * 获取当前用户购物车中的数据
     *
     * @return
     */
    @Override
    public CartRedisVo getCurrentMemberCartData() {
        Long memberId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());

        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(CartConstant.CART_PREFIX);
        String resp = (String) cartOps.get(memberId.toString());
        if (StringUtils.isEmpty(resp)) {
            // 用户购物车中没有商品
            CartRedisVo cartRedisVo = new CartRedisVo();
            cartRedisVo.setItems(Collections.emptyList());
            return cartRedisVo;
        }

        // 购物车中存在数据

        return JSON.parseObject(resp, CartRedisVo.class);
    }

    /**
     * 购物车商品选中与不选中
     *
     * @param productId
     * @param check
     * @return
     */
    @Override
    public boolean checkItem(Long productId, Boolean check) {
        Long memberId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());

        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(CartConstant.CART_PREFIX);

        CartRedisVo cartRedisVo = getCart();
        // 获取购物项数据重新设置
        List<CartItemVo> items = cartRedisVo.getItems();
        for (CartItemVo item : items) {
            if (item.getProductId().equals(productId)) {
                item.setCheck(check);
                break;
            }
        }

        // 重新计算商品总价和商品数量
        int countNum = 0;
        BigDecimal totalAmount = new BigDecimal(0);
        for (CartItemVo item : items) {
            if (item.getCheck()) {
                countNum += item.getCount();
                BigDecimal totalPrice = item.getTotalPrice();
                totalAmount = totalAmount.add(totalPrice);
            }
        }

        cartRedisVo.setItems(items);
        cartRedisVo.setCountNum(countNum);
        cartRedisVo.setTotalAmount(totalAmount);

        String s = JSON.toJSONString(cartRedisVo);
        cartOps.put(memberId.toString(), s);
        return true;
    }

    @Override
    public boolean updateProductCount(Long productId, Integer productCount) {
        Long memberId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());

        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(CartConstant.CART_PREFIX);


        CartRedisVo currentMemberCartData = getCurrentMemberCartData();

        List<CartItemVo> items = currentMemberCartData.getItems();
        for (CartItemVo item : items) {
            if (item.getProductId().equals(productId)) {
                // 修改商品数量和商品总价
                item.setCount(productCount);
                BigDecimal totalPrice = item.getPrice().multiply(new BigDecimal(productCount)).setScale(2, BigDecimal.ROUND_UP);
                item.setTotalPrice(totalPrice);
            }
        }

        currentMemberCartData.setItems(items);


        // 重新计算商品总价和商品数量
        BigDecimal totalAmount = new BigDecimal(0);
        for (CartItemVo item : items) {
            if (item.getCheck()) {
                BigDecimal totalPrice = item.getTotalPrice();
                totalAmount = totalAmount.add(totalPrice);
            }
        }

        currentMemberCartData.setItems(items);
        currentMemberCartData.setTotalAmount(totalAmount);

        String s = JSON.toJSONString(currentMemberCartData);
        cartOps.put(memberId.toString(), s);
        return true;
    }

    @Override
    public boolean delProduct(Long productId) {

        Long memberId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(CartConstant.CART_PREFIX);


        CartRedisVo cart = getCart();

        // 获取所有的商品
        List<CartItemVo> items = cart.getItems();
        for (int i = 0; i < items.size(); i++) {
            CartItemVo item = items.get(i);
            // 删除选中的商品
            if (item.getProductId().equals(productId)) {
                items.remove(i);
            }
        }


        // 重新计算商品总价和商品数量
        BigDecimal totalAmount = new BigDecimal(0);
        int countNum = 0;
        for (CartItemVo item : items) {
            if (item.getCheck()) {
                BigDecimal totalPrice = item.getTotalPrice();
                totalAmount = totalAmount.add(totalPrice);
                countNum += item.getCount();
            }
        }

        cart.setItems(items);
        cart.setCountNum(countNum);
        cart.setTotalAmount(totalAmount);


        String s = JSON.toJSONString(cart);
        cartOps.put(memberId.toString(), s);

        return true;
    }

    // 获取当前用户的购物车
    private CartRedisVo getCart() {
        Long memberId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(CartConstant.CART_PREFIX);

        String o = (String) cartOps.get(memberId.toString());

        return JSON.parseObject(o, CartRedisVo.class);
    }


}
